<template>
  <el-dialog v-model="dialogVisible" :show-close="false" :title="title" width="50%">
    <el-form ref="formRef" :model="state.ruleForm" :rules="rules" label-position="top">
      <el-form-item label="logo" prop="articlePhoto">
        <el-upload action="#" :show-file-list="false" list-type="picture-card" :auto-upload="false"
          :on-change="handleAvatarSuccess">
          <img v-if="uploadImg" :src="uploadImg" class="dialog-avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
          <template #file="{ file }">
            <div>
              <img :src="file.url" alt="" class="dialog-avatar" />
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章标题" prop="articleTitle">
        <el-input v-model="state.ruleForm.articleTitle" clearable placeholder="请输入文章标题" />
      </el-form-item>
      <el-form-item label="日期(与微信公众号日期对应)" prop="articleDate">
        <el-date-picker v-model="state.ruleForm.articleDate" type="date" placeholder="请选择日期" format="YYYY-MM-DD"
          value-format="YYYY-MM-DD" style="width: 100%" />
      </el-form-item>
      <el-form-item label="链接(微信公众号文章路径)" prop="articleUrl">
        <el-input v-model="state.ruleForm.articleUrl" clearable placeholder="请输入文章路径" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm(formRef)">取消</el-button>
        <el-button v-if="type === 'add'" type="primary" @click="submitAdd(formRef)">
          确定
        </el-button>
        <el-button v-else type="primary" @click="submitEdit(formRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onUpdated, reactive, ref } from "vue"
import { FormInstance, FormRules, UploadFile, ElMessage } from "element-plus"
import {postUploadImg} from "@/api/match"
import { postAddNew, postEditNew } from "@/api/base"
import { TypeEnum } from "../../enum";

const props = defineProps(["type", "params"]);
const emits = defineEmits(["submitChange"]);
const formRef = ref<FormInstance>();
const uploadImg = ref("")
const dialogVisible = ref(false);
const state = reactive({
  ruleForm: {
    articlePhoto: "",
    articleType: TypeEnum.News,  // 默认news
    articleTitle: "",
    articleUrl: "",
    articleDate: "",
  }
})
const rules = reactive<FormRules>({
  articleTitle: [
    { required: true, message: "请输入文章标题！", trigger: "blur" },
  ],
  articleDate: [
    { required: true, message: "请选择日期！", trigger: "change" },
  ],
  articleUrl: [
    { required: true, message: "请输入文章路径！", trigger: "blur" },
  ],
})
const title = ref("新增")

// 上传图片成功
const handleAvatarSuccess = async (file: UploadFile) => {
  const res = await postUploadImg({
    "file": file.raw,
    "fileType": "article"
  });
  state.ruleForm.articlePhoto = res.data
  uploadImg.value = URL.createObjectURL(file.raw!)
}
// 提交新增按钮
const submitAdd = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      postAddNew(state.ruleForm).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: res.msg,
          })
          emits("submitChange")
          dialogVisible.value = false
        }
      })
    }
  })
}
// 提交编辑按钮
const submitEdit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const ruleForm = {
        ...state.ruleForm,
        articleType: TypeEnum.News  // 为了兼容以前接口没有传这个字段的情况
      }
      postEditNew(ruleForm).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: res.msg,
          })
          emits("submitChange")
          dialogVisible.value = false
        }
      })
    }
  })
}
// 取消按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogVisible.value = false;
}

onUpdated(() => {
  if (props.type === "add") {
    title.value = "新增"
  } else {
    title.value = "编辑"
    state.ruleForm = props.params
    uploadImg.value = props.params.articlePhoto
    state.ruleForm.articlePhoto = ""
  }
})
defineExpose({
  dialogVisible,
});
</script>
<style lang="scss" scoped>
.dialog-avatar {
  width: 100px;
  height: 100px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
@/api/cantera/config